import React, { Component } from 'react';
import { Platform, Text, TouchableOpacity, View, WebView } from 'react-native';
import Prompt from 'react-native-prompt';
import HeatmapUtils from '../../util/HeatmapUtils';

import styles from './Heatmap.styles';

export default class Heatmap extends Component {
  state = {
    radiusRate: 0.4
  }

  componentDidMount() {
    setTimeout(
      () => {
          const width = this.props.width;
          const height = this.props.height;
          const radius = width > height ? Math.round(height * this.state.radiusRate) : Math.round(width * this.state.radiusRate);
          this.drawPoints();
          this.setState({ width, height, radius});
      }
    );
  }

  /**
   * 图像显示部分点击事件
   * 功能：当点击图像时，获取触摸点坐标，并存储到state.points中
   * @param {*} evt 
   */
  clickEvent(evt) {
    this.setState({promptVisible: true});
    var points = this.state.points;

    if (evt != null) {
      points.push({x: parseInt(evt.nativeEvent.pageX), y: parseInt(evt.nativeEvent.pageY), value: 1});
      var position = points.length - 1;
      this.setState({points, position});
    }
  }

  /**
   * 弹出框取消事件
   * 功能：取消时会将点击时插入的最后一个点去除
   */
  promptCancel() {
      this.setState({ promptVisible: false});

      if (this.state.points && this.state.points.length > 1) {
        this.state.points.pop();
        var position = this.state.points.length - 1;
        this.setState({position});
      }
  }

  /**
   * 弹出框确认事件
   * 功能：点击后获取弹出框输入值value，value用于设置图上点的值，
   * 此值影响图像显示的色彩
   * @param {*} value 
   */
  promptSubmit(value) {

      if (!value) {
        this.state.points.pop();
        var position = this.state.points.length - 1;
        this.setState({position});
      } else {
        this.state.points[this.state.position].value = value;
      }

      this.setState({
        promptVisible: false,
      });

      this.drawPoints();
  }


  test() {

    //当点存在需要加载时，所需参数为原始点集、原始图片长宽值（比例也可，此处使用值）
    this.state.points.push({x: 7, y: 258, value: 1});
    this.state.points.push({x: 109, y: 55, value: 2});
    this.state.points.push({x: 314, y: 31, value: 3});
    let originalHeight = 295;
    let originalWidth = 360;

    let points = [];
    for (let i = 0; i < 4; i++) {
      if (0 == i) {
        points.push(this.state.points[i]);
        continue;
      }
      let point = this.state.points[i];
      points.push({x: parseInt(point.x * (this.props.width / originalWidth)) + 1, y: parseInt(point.y * (this.props.height / originalHeight)) + 1, value: point.value});
    }
    this.state.points = points;
    
    this.drawPoints();
  }

  /**
   * 改变点的状态
   * 功能：改变state中processedPointed的内容去重新绘制热区中的点，
   */
  drawPoints() {
    var points = this.state.points;

    if (null == points) {
        points = [];
        points.push({x: -this.props.width * this.state.radiusRate, y: -this.props.width * this.state.radiusRate, value: 1});
        var position = points.length - 1;
        this.setState({points, position});
    }

    setTimeout(() => {
      var width = this.state.width;
      var height = this.state.height;
      var radius = this.state.radius;
      const processedPoints = HeatmapUtils.generatePoints(points, this.state.radiusRate * this.props.width, 2);
      this.setState({ processedPoints });

    });

    // Forcing heatmap to empty
    this.setState({ processedPoints: null });
  }

  render() {
    let webview = null;
    if (this.state.processedPoints) {
      const uri = Platform.OS === 'ios' ? 'heatmap.html' : 'file:///android_asset/heatmap.html';
      const maxValue = Math.max(...this.state.processedPoints.map((p) => p.value));
      const script = heatmapInputGenerator(this.state.processedPoints, this.state.radius, maxValue, this.props.height, this.props.width);
      webview = <WebView
        source={{ uri: uri }}
        scrollEnabled={false}
        injectedJavaScript={script}
        javaScriptEnabled
      />;
    }

    return (
      <View style={styles.container} >
        <Prompt
          title="输入数值"
          placeholder="正数"
          defaultValue=""
          visible={ this.state.promptVisible }
          onCancel={this.promptCancel.bind(this)}
          onSubmit={ this.promptSubmit.bind(this)}/>
        <TouchableOpacity onPress={this.clickEvent.bind(this)} style={{width: this.props.width, height: this.props.height}}>
           <View style={[styles.webview,{width: this.props.width, height: this.props.height}]} ref='heatmap' >
            { webview }
          </View>
        </TouchableOpacity>
      </View>
    );
  }
}

/**
 * 生成出入webbiew中的脚本
 * @param {*} points 
 * @param {*} radius 
 * @param {*} max 
 * @param {*} screenHeight 
 * @param {*} screenWidth 
 */
const heatmapInputGenerator = (points, radius, max, screenHeight, screenWidth) => {
  return `
    var selector = document.querySelector('.heatmap');
    selector.style.height = ` + screenHeight + ` + 'px';
    selector.style.width = ` + screenWidth + ` + 'px';
    selector.style.backgroundImage = 'url("1.png")';
    selector.style.backgroundRepeat = 'no-repeat';
    selector.style.backgroundSize = '100% 100%';
    var heatmapInstance = h337.create({
      container: selector,
      radius: ${radius},
      opacity: 0.4
    });
    heatmapInstance.setData({
      max: ${max},
      data: ${JSON.stringify(points)}
    });
  `;
};
